package com.common;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.entity.NoteBean;
import com.common.picker.SinglePickUtil;
import com.common.ui.NoteAdapter;
import com.common.ui.NoteGridAdapter;
import com.common.ui.WriteNoteActivity;
import com.common.ui.db.SQLiteDB;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.edit_search_context)
    EditText mEditSearchContext;
    @BindView(R.id.iv_search)
    ImageView mIvSearch;
    @BindView(R.id.tv_order_by)
    TextView mTvOrderBy;
    @BindView(R.id.iv_down)
    ImageView mIvDown;
    @BindView(R.id.tv_note_count)
    TextView mTvNoteCount;
    @BindView(R.id.iv_switch_view)
    ImageView mIvSwitchView;
    @BindView(R.id.core_list_view_id)
    RecyclerView mCoreListViewId;
    @BindView(R.id.core_list_refresh_id)
    SwipeRefreshLayout mCoreListRefreshId;
    private List<NoteBean> mNoteBeanList = new ArrayList<>();
    private boolean isFirst = true;
    private List<String> mOrderBys = Arrays.asList("编辑日期", "创建日期", "标题");
    private String mOrderBy = "update_time";
    private NoteAdapter mNoteAdapter;
    private NoteGridAdapter mNoteGridAdapter;
    private boolean isRecycview = true;
    private Activity mActivity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mActivity = this;
        initAdapter();
        mEditSearchContext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mNoteBeanList.clear();
                mNoteBeanList.addAll(SQLiteDB.getInstance(mActivity).findDataByContent(s.toString(), mOrderBy));
                if (isRecycview) {
                    mNoteAdapter.notifyDataSetChanged();
                } else {
                    mNoteGridAdapter.notifyDataSetChanged();
                }
            }
        });
        updateView();
        mCoreListRefreshId.setEnabled(false);
    }


    private void loadData() {
        mNoteBeanList.clear();
        mNoteBeanList.addAll(SQLiteDB.getInstance(mActivity).findAllData(mOrderBy));
        mTvNoteCount.setText(String.format("%s个备忘录", mNoteBeanList.size()));
        if (isRecycview) {
            mNoteAdapter.notifyDataSetChanged();
        } else {
            mNoteGridAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        if (!isFirst) {
            loadData();
        }
        isFirst = false;
        super.onResume();
    }

    @OnClick({R.id.iv_add_note, R.id.tv_order_by, R.id.iv_switch_view})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_add_note: {
                Intent intent = new Intent(mActivity, WriteNoteActivity.class);
                intent.putExtra(WriteNoteActivity.EXTRA_TYPE, WriteNoteActivity.EXTRA_ADD);
                startActivity(intent);
            }
            break;
            case R.id.tv_order_by: {
                SinglePickUtil singlePickUtil = new SinglePickUtil(mActivity);
                singlePickUtil.show();
                TextView textView = singlePickUtil.findViewById(R.id.tv_title);
                textView.setText("");
                singlePickUtil.resetData(mOrderBys);
                singlePickUtil.setOnSelectedPositionListener(new SinglePickUtil.OnSelectedPositionListener() {
                    @Override
                    public void onSelected(Object selectedValue, int position) {
                        mTvOrderBy.setText(String.format("按%s排序", selectedValue.toString()));
                        switch (position) {
                            case 0:
                                mOrderBy = "update_time";
                                break;
                            case 1:
                                mOrderBy = "add_time";
                                break;
                            case 2:
                                mOrderBy = "title";
                                break;
                        }
                        loadData();
                    }
                });

            }
            break;
            case R.id.iv_switch_view: {
                isRecycview = !isRecycview;
                updateView();
            }
            break;
        }
    }

    private void updateView() {
        if (!isRecycview) {
            mCoreListViewId.setLayoutManager(new GridLayoutManager(mActivity, 3));
            mCoreListViewId.setAdapter(mNoteGridAdapter);
            loadData();
        } else {
            mCoreListViewId.setLayoutManager(new LinearLayoutManager(mActivity));
            mCoreListViewId.setAdapter(mNoteAdapter);
            loadData();
        }
    }

    /**
     * 初始化两个适配器
     */
    private void initAdapter() {
        mNoteGridAdapter = new NoteGridAdapter(mNoteBeanList);
        mNoteAdapter = new NoteAdapter(mNoteBeanList);
        mNoteAdapter.addChildClickViewIds(R.id.tv_delete);
        mNoteGridAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                goToUpdate(position);
            }
        });
        mNoteAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                goToUpdate(position);
            }
        });
        mNoteAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                NoteBean noteBean = mNoteAdapter.getItem(position);
                if (view.getId() == R.id.tv_delete) {
                    if (SQLiteDB.getInstance(mActivity).deleteNote(noteBean.getNote_id())) {
                        loadData();
                    } else {
                        Toast.makeText(mActivity, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private void goToUpdate(int position) {
        NoteBean noteBean = mNoteBeanList.get(position);

        Intent intent = new Intent(mActivity, WriteNoteActivity.class);
        intent.putExtra(WriteNoteActivity.EXTRA_TYPE, WriteNoteActivity.EXTRA_UPDATE);
        intent.putExtra(WriteNoteActivity.EXTRA_CONTENT, noteBean.getContent());
        intent.putExtra(WriteNoteActivity.EXTRA_TITLE, noteBean.getTitle());
        intent.putExtra(WriteNoteActivity.EXTRA_ID, noteBean.getNote_id());
        startActivity(intent);
    }
}
